﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace PlaneClean.CommonHelp
{
    public class CommonTreeHelp<T, G> where G : new()
    {
        /// <summary>
        /// 树形下拉框
        /// </summary>
        /// <param name="List">表列表</param>
        /// <param name="pID">根节点</param>
        /// <param name="value">表字段名对应下拉框value</param>
        /// <param name="label">表字段名对应下拉框label</param>
        /// <param name="parentKey">表字段名对应的父字段名</param>
        /// <returns></returns>
        public List<G> ToTreeMenu(List<T> List, int pID,string value,string label,string parentKey)
        {
            List<G> res = new List<G>();
            if (List == null || List.Count <= 0)
            {
                return res;
            }
            Type ts = List[0].GetType();
            Type tsG = new G().GetType();
            //object v = Convert.ChangeType(Value, ts.GetProperty("child").PropertyType);
            List<T> tempList = List.Where(c => ((int)ts.GetProperty(parentKey).GetValue(c, null)) == pID).ToList();
            if (tempList != null && tempList.Count > 0)
            {
                foreach (var temp in tempList)
                {
                    G g = new G();
                    tsG.GetProperty("value").SetValue(g, (int)ts.GetProperty(value).GetValue(temp, null));
                    tsG.GetProperty("label").SetValue(g, ts.GetProperty(label).GetValue(temp, null).ToString());
                    var m_id = (int)ts.GetProperty(value).GetValue(temp, null);
                    var children = ToTreeMenu(List, (int)ts.GetProperty(value).GetValue(temp, null), value,label, parentKey);
                    if (children != null && children.Count > 0)
                    {
                        tsG.GetProperty("children").SetValue(g, children, null);
                    }

                    res.Add(g);
                }
            }
            return res;
        }
    }
}